import axios from 'axios';

// 创建axios实例
const instance = axios.create({
  baseURL: '/api/v1',
  timeout: 12000,
  headers: { 'Content-Type': 'application/json' },
});

// 请求拦截器：加入 token
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('access_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 可以在这里统一处理响应数据
    return response.data;
  },
  (error) => {
    // 统一错误处理
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，跳转到登录页
          localStorage.removeItem('access_token');
          window.location.href = '/login';
          break;
        case 403:
          // 禁止访问
          console.error('访问被禁止');
          break;
        case 404:
          // 资源不存在
          console.error('请求的资源不存在');
          break;
        case 500:
          // 服务器错误
          console.error('服务器内部错误');
          break;
        default:
          console.error('请求失败', error.response.data);
      }
    } else {
      console.error('网络错误', error.message);
    }
    return Promise.reject(error);
  }
);

// API 方法封装
export const api = {
  // 患者相关
  getPatients: (params) => instance.get('/patients', { params }),
  getPatient: (id) => instance.get(`/patients/${id}`),
  createPatient: (data) => instance.post('/patients', data),
  updatePatient: (id, data) => instance.put(`/patients/${id}`, data),
  deletePatient: (id) => instance.delete(`/patients/${id}`),

  // 血糖相关
  getGlucoseData: (patientId, params) => instance.get(`/glucose/${patientId}`, { params }),
  createGlucoseAlert: (data) => instance.post('/glucose/alert', data),

  // 设备相关
  getDevices: () => instance.get('/devices'),
  upgradeDevice: (id, data) => instance.post(`/devices/${id}/upgrade`, data),

  // 报告相关
  generateReport: (patientId, params) => instance.get(`/reports/${patientId}`, { params }),

  // 系统设置相关
  getThresholds: () => instance.get('/settings/thresholds'),
  updateThresholds: (data) => instance.post('/settings/thresholds', data),
  getRoles: () => instance.get('/settings/roles'),
  updateRoles: (data) => instance.post('/settings/roles', data),
};

export default instance;
